package com.sky.service.impl;

import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class ReportServiceImp implements ReportService {
    @Resource
    OrderMapper orderMapper;
    @Resource
    OrderDetailMapper orderDetailMapper;
    @Resource
    WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO turnover(LocalDate begin, LocalDate end) {
        List<Double> list = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");
        List<String> moon = new ArrayList<>();
        while (!begin.isAfter(end)) {
            String format = formatter.format(begin);
            moon.add(format);
            LocalDateTime s = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime e = LocalDateTime.of(begin, LocalTime.MAX);
            Double turnover = orderMapper.turnover(s, e);
            if (turnover == null) {
                list.add((double) 0);
            } else {
                list.add(orderMapper.turnover(s, e));
            }

            begin = begin.plusDays(1);
        }
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        String count = list.toString().replace("[", "").replace("]", "");
        turnoverReportVO.setTurnoverList(count);
        String moonStr = moon.toString().replace("[", "").replace("]", "");
        turnoverReportVO.setDateList(moonStr);
        return turnoverReportVO;
    }

    @Override
    public UserReportVO userReport(LocalDate begin, LocalDate end) {
        //封装日期
        List<String> moon = new ArrayList<>();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-dd");
        List<Integer> total = new ArrayList<>();
        List<Integer> increase = new ArrayList<>();
        while (!begin.isAfter(end)) {
            String format = dateTimeFormatter.format(begin);
            moon.add(format);
            LocalDateTime s = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime d = LocalDateTime.of(begin, LocalTime.MAX);
            Map<String, LocalDateTime> map = new HashMap<>();
            map.put("end", d);
            Integer all = orderMapper.getUserCount(map);
            if (all == null) {
                all = 0;
            }
            total.add(all);
            map.put("begin", s);
            Integer create = orderMapper.getUserCount(map);
            if (create == null) {
                create = 0;
            }
            increase.add(create);
            begin = begin.plusDays(1);
        }
        String totals = total.toString().replace("[", "").replace("]", "");
        String moons = moon.toString().replace("[", "").replace("]", "");
        String increases = increase.toString().replace("[", "").replace("]", "");

        return UserReportVO.builder().totalUserList(totals).dateList(moons).newUserList(increases).build();
    }

    @Override
    public OrderReportVO orderReport(LocalDate begin, LocalDate end) {
        List<String> moon = new ArrayList<>();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-dd");
        List<Integer> total = new ArrayList<>();
        List<Integer> valid = new ArrayList<>();
        while (!begin.isAfter(end)) {
            String format = dateTimeFormatter.format(begin);
            moon.add(format);
            LocalDateTime s = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime d = LocalDateTime.of(begin, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();

            map.put("end", d);
            map.put("begin", s);

            //获取每天订单数量
            Integer all = orderMapper.getOrderCount(map);
            if (all == null) {
                all = 0;
            }
            total.add(all);
            map.put("status", 5);
            //获取每天有效订单数量
            Integer create = orderMapper.getOrderCount(map);
            if (create == null) {
                create = 0;
            }
            valid.add(create);
            begin = begin.plusDays(1);
        }
        String totals = total.toString().replace("[", "").replace("]", "");
        String moons = moon.toString().replace("[", "").replace("]", "");
        String valids = valid.toString().replace("[", "").replace("]", "");
        //获取总订单数
        Integer total_number = orderMapper.getOrderCount(new HashMap<>());
        //获取总共有效订单数
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("status", 5);
        Integer valid_number = orderMapper.getOrderCount(hashMap);
        //计算有效订单率
        Double p = (double) (valid_number / total_number);

        OrderReportVO build = OrderReportVO.builder().orderCompletionRate(p).orderCountList(totals).dateList(moons).totalOrderCount(total_number).validOrderCount(valid_number).validOrderCountList(valids).build();
        return build;
    }

    @Override
    public SalesTop10ReportVO salesTop10Report(LocalDate begin, LocalDate end) {
        LocalDateTime s = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime e = LocalDateTime.of(end, LocalTime.MAX);
        List<DishSaleCount> dishCount = orderDetailMapper.getDishCount(s, e);
        List<Integer> numberList = new ArrayList<>();
        List<String> nameList = new ArrayList<>();
        for (DishSaleCount dishSaleCount : dishCount) {
            nameList.add(dishSaleCount.getName());
            numberList.add(dishSaleCount.getCount());
        }

        String numbers = numberList.toString().replace("[", "").replace("]", "");
        String names = nameList.toString().replace("[", "").replace("]", "");

        return SalesTop10ReportVO.builder().nameList(names).numberList(numbers).build();
    }


    //下载报表
    @Override
    public void getBusinessData(HttpServletResponse response) {
        /*
         * 获取数据 最近30天的总数据
         */
        LocalDate now = LocalDate.now();
        LocalDateTime start = now.minusDays(30).atStartOfDay();
        LocalDateTime end = now.minusDays(1).atTime(LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(start, end);
        /*
         * 获取表格
         * */
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        XSSFWorkbook xssfWorkbook;
        try {
            xssfWorkbook = new XSSFWorkbook(resourceAsStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        XSSFSheet sheet = xssfWorkbook.getSheetAt(0);
        /*
         * 设置表格顶部总览数据
         * */
        XSSFRow date = sheet.getRow(1);
        String s1 = start.toLocalDate().toString() + ":" + end.toLocalDate().toString();
        date.getCell(1).setCellValue(s1);
        XSSFRow row = sheet.getRow(3);
        row.getCell(2).setCellValue(businessData.getTurnover());
        row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
        row.getCell(6).setCellValue(businessData.getNewUsers());
        XSSFRow row1 = sheet.getRow(4);
        row1.getCell(2).setCellValue(businessData.getValidOrderCount());
        row1.getCell(4).setCellValue(businessData.getUnitPrice());


        /*
         *
         * 获取每一天的数据
         * */

        int start_line = 7; //明细数据的表格下标

        while (!start.isAfter(end)) {
            LocalDate temp = start.toLocalDate();
            LocalDateTime s = temp.atStartOfDay();
            LocalDateTime e = temp.atTime(LocalTime.MAX);
            BusinessDataVO businessData1 = workspaceService.getBusinessData(s, e);
            XSSFRow row2 = sheet.getRow(start_line);
            row2.getCell(1).setCellValue(String.valueOf(temp));
            row2.getCell(2).setCellValue(businessData1.getTurnover());
            row2.getCell(3).setCellValue(businessData1.getValidOrderCount());
            row2.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
            row2.getCell(5).setCellValue(businessData1.getUnitPrice());
            row2.getCell(6).setCellValue(businessData1.getNewUsers());
            start_line++;
            start = start.plusDays(1);

        }
        try {
            xssfWorkbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try{
            xssfWorkbook.close();
            resourceAsStream.close();
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
